<template>
  <div>
    <el-dialog
      :title="title"
      :width="dialogWidth"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="visible"
      :before-close="BeforeClose"
    >
      <el-form
        :model="form"
        ref="form"
        v-loading="loading"
        :rules="rules"
        :class="method==='view'?'readonly':''"
        :disabled="method==='view'"
        label-width="110px"
      >
        <el-row :gutter="15">
          <el-col :span="22">
            <el-form-item
              label="标题"
              prop="title"
            >
              <el-input
                v-model="form.title"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="发布时间"
              prop="publishTime"
            >
              <el-date-picker
                v-model="form.publishTime"
                style="width:100%;"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="排序选择"
              prop="sortOrder"
            >
              <el-input-number
                v-model="form.sortOrder"
                :step="1"
                step-strictly
                style="width:100%;"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="备注"
              prop="summary"
            >
              <el-input
                v-model="form.summary"
                type="textarea"
                placeholder="请输入"
                :rows="4"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item
              label="上传图片"
              prop="files"
            >
              <el-upload
                ref="upload"
                action=""
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :http-request="handleChanged"
                :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/jpg,image/png"
              >
                <i class="el-icon-plus"></i>
                <!-- <div
                  class="el-upload__tip"
                  slot="tip"
                >只能上传jpg/png文件，且分辨率为153*320</div> -->
                <div
                  class="el-upload__tip"
                  slot="tip"
                >只能上传jpg/png文件</div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img
                  width="100%"
                  :src="dialogImageUrl"
                  alt=""
                >
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="BeforeClose">取 消</el-button>
        <el-button
          type="primary"
          v-if="method != 'view'"
          @click="doSubmit()"
        >提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj } from '@/api/information/content/person'
export default {
  data () {
    return {
      title: '',
      method: '',
      visible: false,
      dialogWidth: '35%',
      loading: false,
      formLabelWidth: '80px',
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        title: [
          { required: true, message: '请填写标题' }
        ],
        summary: [
          { required: true, message: '请填写推送内容' }
        ],
        sortOrder: [
          { required: true, message: '请填写排序' }
        ],
        publishTime: [
          { required: true, message: '请选择发布时间' }
        ],
      },
      form: {
        id: '',
        title: '',
        summary: '',
        sortOrder: 0,
        publishTime: '',
        msgType: 3,//(1.推送消息 2.公告消息 3.内容消息)
        sysNewFile: {
          fileId: ''
        },
      },
      fileList: [],
      fileLists: []
    }
  },
  components: {
  },
  methods: {
    handleExceed (files) {
      this.$message.warning(`当前导入限制只能上传 1 个文件`)
    },
    BeforeClose () {
      this.fileList = []
      this.fileLists = []
      this.visible = false
    },
    handleChanged (raw) {
      this.fileLists.push(raw.file);
      // this.fileList = raw
    },
    init (method, id) {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.fileLists = []
      this.fileList = []
      this.method = method
      this.form.id = id
      if (method === 'add') {
        this.title = `新建内容`
      } else if (method === 'edit') {
        this.title = '修改内容'
      } else if (method === 'view') {
        this.title = '查看内容'
      }
      this.visible = true;

      //获取详情
      this.loading = false
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (method === 'view' || method === 'edit') { // 查看
          this.form = JSON.parse(JSON.stringify(id))
          if (id.url) {
            id.url.split(',').forEach((item, index) => {
              this.fileList.push({ name: index, url: item })
            })
          }
        }
      })

    },
    // 表单提交
    doSubmit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let formdata = new FormData()
          for (var key in this.form) {
            if (this.form[key] || this.form[key] === 0) {
              if (typeof this.form[key] === "object") {
                formdata.append(key, JSON.stringify(this.form[key]))
              } else {
                formdata.append(key, this.form[key])
              }
            }
          }
          this.fileLists.forEach(function (file) {
            // 因为要上传多个文件，所以需要遍历一下才行
            formdata.append('file', file);
          })
          if (this.form.id) {
            putObj(formdata).then(data => {
              this.$message.success('修改成功')
              this.BeforeClose()
              this.$emit('refreshDataList')
            });
          } else {
            addObj(formdata).then(data => {
              this.$message.success('添加成功')
              this.BeforeClose()
              this.$emit('refreshDataList')
            })
          }
        }
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeAvatarUpload (file) {
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type)

      if (!isJPG) {
        this.$message.error('上传图片格式不对!');
      }
      const isSize = new Promise(function (resolve, reject) {
        let height = 153;
        let width = 320;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function () {
          // let valid = img.height == height && img.width == width;
          let valid = false
          valid ? resolve() : reject();
        }
        img.src = _URL.createObjectURL(file);
      }).then(() => {
        return file;
      }, () => {
        this.$message.error('上传的图片必须是153*320!')
        return Promise.reject();
      })
      return isJPG && isSize;
    }
  }
}
</script>

